var express = require("express");
var router = express.Router();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const uuid = require("uuid");
const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/img/avatar");
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = uuid.v4();
    cb(null, uniqueSuffix + path.extname(file.originalname));
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fieldSize: 5 * 1024 * 1024 * 1024,
  },
});


router.get("/getInfo", async (req, res) => {
  const user_id = req.auth.user.user_id;
  const data = await prisma.user_all.findMany({
    where: {
      user_id: user_id,
    },
  });
  if (data[0].avatar == null) {
    data[0].avatar = "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
  }
  res.send(data[0]);
});

router.post("/updateUser", async (req, res) => {
  const user_id = req.auth.user.user_id;
  const { user_name, phone, email, address } = req.body;
  try {
    const updateUser = await prisma.user_all.update(
      {
        where: {
          user_id: user_id
        },
        data: {
          user_name: user_name,
          phone: phone,
          email: email,
          address: address,
        },
      }
    );
    if (updateUser) {
      res.json({msg:1})
    }
  } catch (error) {
    res.json({msg:0})
  }
})

router.post("/updateAvatar", upload.single("avatar"), async (req, res) => {
  let data = {};
  const user_id = req.auth.user.user_id;
  if (req.file != null) data.avatar = "http://localhost:3000/img/avatar/" + req.file.filename;
  const user = await prisma.user_all.update({
    where: {
      user_id: user_id,
    },
    data: data,
  });
  res.json(user);
})

module.exports = router;
